import 'package:flutter/material.dart';

import '../table.dart';

/// 单元格绘制器基类，实现了点击，背景、边框的绘制逻辑
abstract class KqBaseCellRender<T extends KqBaseCellConfig> extends CellRender {
  /// 单元格配置构建器，返回指定单元格配置
  final T? Function(int row, int column)? cellConfigBuilder;

  KqBaseCellRender({this.cellConfigBuilder});

  @override
  Widget build(BuildContext context, int row, int column, double width,
      double height, bool isLongPress) {
    T? config = cellConfigBuilder?.call(row, column);
    // 此处不能使用Container,否则只要Container设置背景演示，buildBody如果有如InkWell带水波纹的点击，则水波纹无效
    return Container(
      width: width,
      height: height,
      clipBehavior: Clip.antiAlias,
      decoration: BoxDecoration(
        border: getCellBorder(row, column, config),
        color: getBackground(row, column, isLongPress, config),
      ),
      child: buildBody(context, row, column, width, height, isLongPress),
    );
  }

  /// 构建单元格内容
  Widget buildBody(BuildContext context, int row, int column, double width,
      double height, bool isLongPress);

  /// 获取单元格配置
  @protected
  T? getConfig(int row, int column) => cellConfigBuilder?.call(row, column);

  /// 获取单元格的边框
  @protected
  Border? getCellBorder(int row, int column, T? config) {
    BorderSide top;
    BorderSide left;
    BorderSide right;
    BorderSide bottom;
    var border = config?.border;
    if (border != null) {
      top = row == 0
          ? BorderSide(color: border.top.color, width: border.top.width * 2)
          : border.top;
      bottom = row == (table?.rowCount ?? 0) - 1
          ? BorderSide(
              color: border.bottom.color, width: border.bottom.width * 2)
          : border.bottom;
      left = column == 0
          ? BorderSide(color: border.left.color, width: border.left.width * 2)
          : border.left;
      right = column == (table?.columnCount ?? 0) - 1
          ? BorderSide(color: border.right.color, width: border.right.width * 2)
          : border.right;
      border = Border(top: top, left: left, right: right, bottom: bottom);
    }
    return border;
  }

  /// 获取单元格背景颜色
  @protected
  Color? getBackground(int row, int column, bool isLongPress, T? config) {
    if (isLongPress) {
      return config?.longPressBackground ?? config?.background;
    }

    return config?.background;
  }
}

/// 单元格配置项
class KqBaseCellConfig {
  /// 单元格边框
  Border? border;

  /// 单元格背景颜色
  Color? background;

  /// 长按时单元格背景颜色
  Color? longPressBackground;

  KqBaseCellConfig({this.border, this.background, this.longPressBackground});
}
